﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.IO;
using System.Text;
using JiaBao.Core;
using JiaBao.Core.Data;
using JiaBao.Data.Initializers;

namespace JiaBao.Data
{
    /// <summary>
    /// SQLServer数据库提供者
    /// </summary>
    public class SqlServerDataProvider : IDataProvider
    {

        #region 方法


        /// <summary>
        /// 初始化EF框架ConnectionFactory
        /// </summary>
        public virtual void InitConnectionFactory()
        {
            var connectionFactory = new SqlConnectionFactory();
#pragma warning disable 0618//取消警告
            Database.DefaultConnectionFactory = connectionFactory;
        }

        /// <summary>
        /// 初始化数据库引擎
        /// </summary>
        public virtual void InitDatabase()
        {
            InitConnectionFactory();
            SetDatabaseInitializer();


        }

        /// <summary>
        /// 数据库初始化程序
        /// </summary>
        public virtual void SetDatabaseInitializer()
        {
            //通过一些表名来确认已经安装数据库 
            var tablesToValidate = new[] { "Customer" };
            var customCommands = new List<string>();

            //索引
            customCommands.AddRange(ParesCommands(CommonHelper.MapPath("/App_Data/Install/SqlServer.Indexes.sql"), false));
            //储过程
            customCommands.AddRange(ParesCommands(CommonHelper.MapPath("/App_Data/Install/SqlServer.StoredProcedures.sql"), false));

            var initializer = new CreateTablesIfNotExist<JiaBaoObjectContext>(tablesToValidate, customCommands.ToArray());
            Database.SetInitializer(initializer);

        }
        #endregion

        #region 内部方法

        /// <summary>
        /// 解析SQL文件文本
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="throwExceptionIfNonexists"></param>
        /// <returns></returns>
        protected virtual string[] ParesCommands(string filePath, bool throwExceptionIfNonexists)
        {
            if (!File.Exists(filePath))
            {
                if (throwExceptionIfNonexists)
                    throw new ArgumentException(string.Format("文件不存在 [{0}]", filePath));

                return new string[0];
            }
            var statements = new List<string>();
            using (var stream = File.OpenRead(filePath))
            using (var read = new StreamReader(stream))
            {
                string statement;
                while ((statement = ReadNextStatementFromStream(read)) != null)
                {
                    statements.Add(statement);
                }
            }

            return statements.ToArray();
        }

        /// <summary>
        /// 读取一行 处理 GO
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        protected virtual string ReadNextStatementFromStream(StreamReader reader)
        {
            var sb = new StringBuilder();
            while (true)
            {
                var lineOfText = reader.ReadLine();
                if (lineOfText == null)
                {
                    if (sb.Length > 0)
                        return sb.ToString();

                    return null;
                }

                if (lineOfText.TrimEnd().ToUpper() == "GO")
                    break;

                sb.Append(lineOfText + Environment.NewLine);
            }
            return sb.ToString();
        }


        #endregion
    }
}
